#!/bin/bash

# gRPC双向流项目构建脚本

echo "🔧 检查依赖..."

# 检查protoc
if command -v protoc >/dev/null 2>&1; then
    PROTOC_VERSION=$(protoc --version)
    echo "✅ protoc 已安装: $PROTOC_VERSION"
else
    echo "❌ protoc 未安装"
    echo "请安装 Protocol Buffers:"
    echo "  macOS: brew install protobuf"
    echo "  Ubuntu: sudo apt-get install protobuf-compiler"
    exit 1
fi

# 检查grpc_cpp_plugin
if command -v grpc_cpp_plugin >/dev/null 2>&1; then
    echo "✅ grpc_cpp_plugin 已安装"
else
    echo "❌ grpc_cpp_plugin 未安装"
    echo "请安装 gRPC:"
    echo "  macOS: brew install grpc"
    echo "  Ubuntu: sudo apt-get install libgrpc++-dev"
    exit 1
fi

# 检查gRPC库
if pkg-config --exists grpc++; then
    GRPC_VERSION=$(pkg-config --modversion grpc++)
    echo "✅ gRPC库已正确安装: $GRPC_VERSION"
else
    echo "❌ gRPC库未找到"
    echo "请安装 gRPC 开发库:"
    echo "  macOS: brew install grpc"
    echo "  Ubuntu: sudo apt-get install libgrpc++-dev"
    exit 1
fi

echo ""
echo "📁 创建目录结构..."
mkdir -p build include

echo ""
echo "🧹 清理之前的构建文件..."
rm -rf build/*

echo ""
echo "📝 生成protobuf代码..."
protoc --cpp_out=build -Isrc src/chat.proto
if [ $? -ne 0 ]; then
    echo "❌ protobuf代码生成失败"
    exit 1
fi

echo "📝 生成gRPC代码..."
protoc --grpc_out=build --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` -Isrc src/chat.proto
if [ $? -ne 0 ]; then
    echo "❌ gRPC代码生成失败"
    exit 1
fi

echo "📝 复制头文件到include目录..."
cp build/chat.pb.h build/chat.grpc.pb.h include/

echo ""
echo "🔨 编译项目..."

# 编译protobuf生成的文件
echo "编译 chat.pb.cc..."
g++ -std=c++17 `pkg-config --cflags protobuf grpc` -Iinclude -Ibuild -c build/chat.pb.cc -o build/chat.pb.o

echo "编译 chat.grpc.pb.cc..."
g++ -std=c++17 `pkg-config --cflags protobuf grpc` -Iinclude -Ibuild -c build/chat.grpc.pb.cc -o build/chat.grpc.pb.o

# 编译服务器
echo "编译 server.cpp..."
g++ -std=c++17 `pkg-config --cflags protobuf grpc` -Iinclude -Ibuild -c src/server.cpp -o build/server.o

# 编译客户端
echo "编译 client.cpp..."
g++ -std=c++17 `pkg-config --cflags protobuf grpc` -Iinclude -Ibuild -c src/client.cpp -o build/client.o

# 链接服务器
echo "链接 chat_server..."
g++ build/chat.pb.o build/chat.grpc.pb.o build/server.o `pkg-config --libs protobuf grpc++ grpc` -o build/chat_server

# 链接客户端
echo "链接 chat_client..."
g++ build/chat.pb.o build/chat.grpc.pb.o build/client.o `pkg-config --libs protobuf grpc++ grpc` -o build/chat_client

echo ""
echo "✅ 构建成功!"
echo ""
echo "🚀 使用方法:"
echo "  启动服务器: ./build/chat_server"
echo "  启动客户端: ./build/chat_client"